package com.meicet.adapter.dialog

import android.content.Context
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.Keep
import androidx.viewbinding.ViewBinding
import com.lxj.xpopup.animator.PopupAnimator
import com.lxj.xpopup.animator.ScaleAlphaAnimator
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupAnimation
import com.lxj.xpopup.util.XPopupUtils
import com.meicet.adapter.R

/**
 * 可以设置dialog到任意位置
 */
@Keep
abstract class DialogBinding<T : ViewBinding>(
    context: Context,
    val gravity: Int = Gravity.CENTER
) : BasePopupView(context) {

    lateinit var binding: T
    private val centerPopupContainer: FrameLayout by lazy { findViewById(R.id.centerPopupContainer) }
    override fun getInnerLayoutId() = R.layout._dialog_base_popup_view
    private fun addInnerContent() {
        binding = initBinding(centerPopupContainer)
        val layoutP = binding.root.layoutParams as? LayoutParams
        layoutP?.gravity = gravity
        binding.root.layoutParams = layoutP
        // 这里由子类填充布局   Binding.inflate(LayoutInflater.from(context),rootView,true)

    }

    override fun initPopupContent() {
        super.initPopupContent()
        if (centerPopupContainer.childCount == 0) addInnerContent()
        popupContentView.translationX = popupInfo.offsetX.toFloat()
        popupContentView.translationY = popupInfo.offsetY.toFloat()
        XPopupUtils.applyPopupSize(
            popupContentView as ViewGroup,
            maxWidth,
            maxHeight,
            popupWidth,
            popupHeight,
            null
        )
    }

//    override fun applyDarkTheme() {
//        super.applyDarkTheme()
//        centerPopupContainer.background = XPopupUtils.createDrawable(
//            resources.getColor(R.color._xpopup_dark_color),
//            popupInfo.borderRadius
//        )
//    }
//
//    override fun applyLightTheme() {
//        super.applyLightTheme()
//        centerPopupContainer.background = XPopupUtils.createDrawable(
//            resources.getColor(R.color._xpopup_light_color),
//            popupInfo.borderRadius
//        )
//    }

    abstract fun initBinding(rootView: FrameLayout): T



//    override fun getMaxWidth(): Int {
//        return if (popupInfo.maxWidth == 0) (XPopupUtils.getAppWidth(context) * 0.8f).toInt() else popupInfo.maxWidth
//    }

    override fun getPopupAnimator(): PopupAnimator? {
        return ScaleAlphaAnimator(
            popupContentView,
            animationDuration,
            PopupAnimation.ScaleAlphaFromCenter
        )
    }
}
